import axios from 'axios';
// 使用 import type 导入 options 类型，避免 ts(1484) 错误
import type {options} from '@/interface/interface';
import { ServiceType, getBaseURL } from '@/config/api';

// Java后端服务 (地图数据、案例数据、Neo4j图谱等)
const javaService = axios.create({
  baseURL: 'http://localhost:8080',
});

// FastAPI后端服务 (AI聊天查询)
const fastApiService = axios.create({
  baseURL: 'http://localhost:5001',
});

// Java后端请求拦截器
javaService.interceptors.request.use(
  (config) => {
    return config;
  },
  (error) => {
    console.error('Java Backend Request error:', error);
    return Promise.reject(error);
  }
);

// Java后端响应拦截器
javaService.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    console.error('Java Backend Response error:', error);
    return Promise.reject(error);
  }
);

// FastAPI后端请求拦截器
fastApiService.interceptors.request.use(
  (config) => {
    return config;
  },
  (error) => {
    console.error('FastAPI Request error:', error);
    return Promise.reject(error);
  }
);

// FastAPI后端响应拦截器
fastApiService.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    console.error('FastAPI Response error:', error);
    return Promise.reject(error);
  }
);

// 通用请求函数 - 默认使用Java后端
export const request = (options: options) => {
  if (options.method.toLowerCase() === 'get') {
    options.params = options.data;
    delete options.data;
  }
  return javaService(options).catch((error) => {
    console.error('Request failed:', error);
    throw error;
  });
};

// AI聊天专用请求函数 - 使用FastAPI后端
export const aiRequest = (options: options) => {
  if (options.method.toLowerCase() === 'get') {
    options.params = options.data;
    delete options.data;
  }
  return fastApiService(options).catch((error) => {
    console.error('AI Request failed:', error);
    throw error;
  });
};

// 通用请求函数 - 根据服务类型选择后端
export const serviceRequest = (serviceType: ServiceType, options: options) => {
  const service = serviceType === ServiceType.FASTAPI ? fastApiService : javaService;

  if (options.method.toLowerCase() === 'get') {
    options.params = options.data;
    delete options.data;
  }

  return service(options).catch((error) => {
    console.error(`${serviceType} Request failed:`, error);
    throw error;
  });
};
